<?php

namespace App\Http\Controllers\Admin;
use DB;
use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;
use Gregwar\Captcha\CaptchaBuilder;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    //显示后台登录页面
    public function getIndex(){
    	//解析模板
    	return view('Admin.login.index');
    }
    //检测用户名 密码 验证码是否正确
    public function postCheck(LoginRequest $request)
    {
    	// dd($request->all());
    
    	// 根据用户名查询用户
    	$user = DB::table('adminuser')->where('username',$request->input('username'))->first();
    	// dd($user);
    	if(empty($user)){
    		return back()->with('error','用户名或密码不正确');
    	}

    	if($request->input('password') != $user->password){
    		return back()->with('error','用户名或密码不正确');
    	}

    	//检测验证码是否正确
    	$v = $request->input('vcode');
    	// dd($v);
    	$vcode = $request->session()->get('Vcode');
        // dd($vcode);
        if($v == $vcode){
        	session(['id'=>$user->id]);
   			return redirect('/admin/')->with('success','欢迎'.$user->username.'登录');
        }else{
        	return back()->with('error','验证码不正确');
        }
    }

    //验证码
    public function vcode(){
    	// echo '222';
    	 ob_clean();//清除输出缓存区的内容
	    //生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();

        //把内容存入session
        session(['Vcode'=>$phrase]);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();

       //看到图片输出 需要die
    }

    //退出后台
    public function getExit(){
        // echo '2222';
        session()->forget('id');
        $id = session()->has('id');
        // dd($id);
        if($id){
            return redirect('/admin/');
        }else{
            return redirect('/admin/login/index');

        }
    }
}
